package zhtt;

import org.hibernate.Session;
import org.hibernate.transform.ResultTransformer;
import org.hibernate.transform.Transformers;
import org.junit.Before;
import org.junit.Test;

import java.util.List;
import java.util.Map;

/**
 * Created by zhtt on 2017/4/10.
 */
public class StudentJunitTest {

    private Session session;

    @Before
    public void setUp(){
        session=HbnUtil.getSession();
    }

    @Test/** 添加测试数据  **/
    public void initTestData(){
        try{
            session.beginTransaction();
            for(int i=0;i<10;i++){
                session.save(new Student("name"+i,20+i,80+i));
            }
            session.getTransaction().commit();
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Test/** SQL查询 **/
    public void sql(){
        try{
            session.beginTransaction();
            String sql="select * from zhtt0_student ";//用表名
            List<Student> studentList=session.createSQLQuery(sql).addEntity(Student.class).list();
            for(Student student:studentList){
                System.out.println(student);
            }
            session.getTransaction().commit();
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Test/** SQL查询 返回MapList **/
    public void sql2(){
        try{
            session.beginTransaction();
            String sql="select * from zhtt0_student ";//用表名
            List<Map<String,Object>> studentList=session.createSQLQuery(sql).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).list();
            for(Map<String,Object> student:studentList){
                System.out.println(student);
            }
            session.getTransaction().commit();
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Test /** HQL查询  Hibernate query language **/
    public void hql(){
        try{
           session.beginTransaction();
            String hql="from Student";//用类名
            List<Student> studentList=session.createQuery(hql).list();
            for(Student student:studentList){
                System.out.println(student);
            }
            session.getTransaction().commit();
        }catch (Exception e){

        }
    }

    @Test /** Query By Criteria **/
    public void qbc(){
        try{
            session.beginTransaction();
            List<Student> studentList=session.createCriteria(Student.class).list();
            for(Student student:studentList){
                System.out.println(student);
            }
            session.getTransaction().commit();
        }catch (Exception e){

        }
    }

    @Test /** Query By Criteria **/
    public void qbc1(){
        try{
            session.beginTransaction();
            session.getTransaction().commit();
        }catch (Exception e){

        }
    }

}
